<template>
  <div class="app-container">
    <!-- 操作 -->
    <el-row style="margin-bottom: 10px;">
      <!-- 搜索 -->
      <div v-if="showSearch" class="filter-container" style="display: inline-block">
        <el-form :inline="true" :model="listQuery" class="form-inline">
          <el-form-item label="">
            <el-input v-model="listQuery.phone" placeholder="手机号" clearable size="small"/>
          </el-form-item>
          <el-form-item label="">
            <el-input v-model="listQuery.userName" placeholder="用户名" clearable size="small"/>
          </el-form-item>
          <el-form-item label="启用">
            <el-select v-model="listQuery.isEnabled" placeholder="启用状态" default-first-option size="small">
              <el-option label="全部" value="-1"/>
              <el-option label="启用" value="1"/>
              <el-option label="禁用" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item label="删除">
            <el-select v-model="listQuery.isDel" placeholder="删除状态" default-first-option size="small">
              <el-option label="全部" value="-1"/>
              <el-option label="正常" value="0"/>
              <el-option label="删除" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item label="注册">
            <el-select v-model="listQuery.regTime" placeholder="注册时间" default-first-option size="small">
              <el-option label="全部" value="all"/>
              <el-option label="昨天" value="yesterday"/>
              <el-option label="今天" value="today"/>
              <el-option label="本周" value="week"/>
              <el-option label="本月" value="month"/>
              <el-option label="本季度" value="quarter"/>
              <el-option label="本年" value="year"/>
              <el-option label="自定义" value="custom"/>
            </el-select>
          </el-form-item>
          <el-form-item v-if="listQuery.regTime === 'custom'" label="">
            <el-date-picker v-model="dateTime" :picker-options="pickerOptions" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" align="right" clearable size="small"/>
          </el-form-item>
          <el-form-item>
            <el-button v-waves type="primary" icon="el-icon-search" size="small" @click="handleFilter">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-waves type="warning" icon="el-icon-refresh" size="small" @click="handleFilterClear">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-col :xs="24" :sm="24" :lg="24">
        <el-tooltip content="刷新" placement="top">
          <el-button v-waves type="warning" icon="el-icon-refresh" circle @click="handleFilterClear"/>
        </el-tooltip>
        <el-tooltip content="搜索" placement="top">
          <el-button v-waves type="primary" icon="el-icon-search" circle @click="showSearch = !showSearch"/>
        </el-tooltip>
        <el-tooltip content="删除" placement="top">
          <el-button v-waves :loading="deleting" :disabled="buttonDisabled" type="danger" icon="el-icon-delete" circle @click="handleDeleteAll"/>
        </el-tooltip>
        <el-tooltip content="还原" placement="top">
          <el-button v-waves :loading="deleting" :disabled="buttonDisabled" type="success" icon="el-icon-check" circle @click="handleBackAll"/>
        </el-tooltip>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      :fit="true"
      border
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="ID" align="center" width="60" prop="id" sortable="custom" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" min-width="60px" fixed>
        <template slot-scope="scope">
          <img :src="scope.row.avatar" class="link-type" style="height: 40px" @click="handleImg(scope.row.avatar)">
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="100px" prop="userName" fixed>
        <template slot-scope="scope">
          <span>{{ scope.row.userName }}|{{ scope.row.nickName || "" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="100px">
        <template slot-scope="scope">
          <span>{{ scope.row.sex | sexFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" width="160px" sortable="custom" prop="regTime">
        <template slot-scope="scope">
          <span>{{ scope.row.regTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" width="160px" sortable="custom" prop="loginTime">
        <template slot-scope="scope">
          <span>{{ scope.row.loginTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" width="160px" sortable="custom" prop="loginIp">
        <template slot-scope="scope">
          <span>{{ scope.row.loginIp }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核" width="150px" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isCheck"
            :active-value="1"
            :inactive-value="0"
            @change="handleModifyCheckStatus(scope.row,scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="启用/禁用" width="150px" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isEnabled"
            :active-value="1"
            :inactive-value="0"
            @change="handleModifyStatus(scope.row,scope.$index)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120px" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button v-waves type="primary" icon="el-icon-edit-outline" circle @click="handleUpdate(scope.row.id,scope.$index)"/>
          </el-tooltip>
          <el-tooltip v-if="!scope.row.isDel" content="删除" placement="top">
            <el-button v-waves :loading="scope.row.delete" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row.id,scope.$index)"/>
          </el-tooltip>
          <el-tooltip v-else content="还原" placement="top">
            <el-button v-waves :loading="scope.row.back" type="success" icon="el-icon-check" circle @click="handleBack(scope.row.id,scope.$index)"/>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination v-show="total>0" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.psize" :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </div>
    <el-dialog :visible.sync="infoFormVisible" title="修改用户">
      <el-form label-position="right" label-width="100px" >
        <el-form-item label="用户编号" prop="orderNo">
          <el-input v-model="temp.id" :disabled="true"/>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="temp.userName" :disabled="true"/>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="temp.nickName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="infoFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUserInfo">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, change, getInfo, saveInfo, delAll, backAll } from '@/api/user'
import waves from '@/directive/waves'
import { getArrByKey, tree } from '@/utils'
import openWindow from '@/utils/openWindow'

export default {
  name: 'User',
  components: { },
  directives: {
    waves
  },
  filters: {
    sexFilter(sex) {
      const sexMap = {
        0: '保密',
        1: '男',
        2: '女'
      }
      return sexMap[sex]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      selectedRows: null,
      listLoading: true,
      deleting: false,
      showSearch: false,
      buttonDisabled: true,
      listQuery: {
        page: 1,
        psize: 10,
        sort: 'id desc',
        phone: '',
        userName: '',
        isEnabled: '-1',
        isDel: '-1',
        regTime: 'all',
        startTime: '',
        endTime: ''
      },
      dateTime: '',
      currentId: -1,
      currentIndex: -1,
      infoFormVisible: false,
      temp: {
        id: 0,
        userName: '',
        nickName: ''
      }
    }
  },
  watch: {
    dateTime: function(val) {
      this.listQuery.startTime = val[0]
      this.listQuery.endTime = val[1]
    }
  },
  created() {
    this.fetchList()
  },
  methods: {
    fetchList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchList()
    },
    handleFilterClear() {
      this.listQuery = {
        page: 1,
        psize: 10,
        sort: 'id desc',
        phone: '',
        userName: '',
        isEnabled: '-1',
        isDel: '-1',
        regTime: 'all',
        startTime: '',
        endTime: ''
      }
      this.dateTime = ''
      this.fetchList()
    },
    handleImg(img) {
      openWindow(img, '图片预览', '500', '400')
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop !== null) {
        this.listQuery.sort = prop + ' ' + (order === 'ascending' ? 'asc' : 'desc')
        this.fetchList()
      }
    },
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.buttonDisabled = false
      } else {
        this.buttonDisabled = true
      }
      this.selectedRows = val
    },
    handleSizeChange(val) {
      this.listQuery.psize = val
      this.fetchList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchList()
    },
    handleDelete(id, index) {
      const _this = this
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        _this.$set(_this.list[index], 'delete', true)
        change(id, 'isDel', 1).then(response => {
          if (response.status === 1) {
            _this.fetchList()
            _this.$notify.success('删除成功')
          } else {
            _this.$notify.error('删除失败')
          }
          const delObj = { 'delete': false }
          _this.list = tree.upadteArr(_this.list, 'id', id, delObj)
        }).catch((error) => {
          const delObj = { 'delete': false }
          _this.list = tree.upadteArr(_this.list, 'id', id, delObj)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleDeleteAll() {
      const _this = this
      if (this.selectedRows.length > 0) {
        this.$confirm('此操作将删除这些用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          _this.deleting = true
          const ids = getArrByKey(_this.selectedRows, 'id')
          const idstr = ids.join(',')
          delAll({ ids: idstr }).then(response => {
            if (response.status === 1) {
              _this.fetchList()
              _this.$message.success(response.msg)
            } else {
              _this.$message.error(response.msg)
            }
            _this.deleting = false
          }).catch((error) => {
            _this.deleting = false
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        _this.$message.error('请选择要删除的数据')
      }
    },
    handleBack(id, index) {
      const _this = this
      _this.$set(_this.list[index], 'back', true)
      change(id, 'isDel', 0).then(response => {
        if (response.status === 1) {
          _this.fetchList()
          _this.$notify.success('还原成功')
        } else {
          _this.$notify.error('还原失败')
        }
        const delObj = { 'back': false }
        _this.list = tree.upadteArr(_this.list, 'id', id, delObj)
      }).catch((error) => {
        const delObj = { 'back': false }
        _this.list = tree.upadteArr(_this.list, 'id', id, delObj)
      })
    },
    handleBackAll() {
      const _this = this
      if (this.selectedRows.length > 0) {
        _this.deleting = true
        const ids = getArrByKey(_this.selectedRows, 'id')
        const idstr = ids.join(',')
        backAll({ ids: idstr }).then(response => {
          if (response.status === 1) {
            _this.fetchList()
            _this.$message.success(response.msg)
          } else {
            _this.$message.error(response.msg)
          }
          _this.deleting = false
        }).catch((error) => {
          _this.deleting = false
        })
      } else {
        _this.$message.error('请选择要删除的数据')
      }
    },
    handleUpdate(id, index) {
      getInfo(id).then(response => {
        if (response.status === 1) {
          this.currentId = id
          this.currentIndex = index
          this.temp.id = response.data.id
          this.temp.userName = response.data.userName
          this.temp.nickName = response.data.nickName
          this.temp.editBalance = this.temp.editIntegral = 0
          this.infoFormVisible = true
        }
      })
    },
    saveUserInfo() {
      this.listLoading = true
      const data = {
        id: this.temp.id,
        nickName: this.temp.nickName,
        editBalance: this.temp.editBalance,
        editIntegral: this.temp.editIntegral
      }
      saveInfo(data).then(response => {
        if (response.status === 1) {
          const temp = this.list[this.currentIndex]
          temp.nickName = response.data.nickName
          temp.balance = response.data.balance
          temp.integral = response.data.integral
          this.infoFormVisible = false
        }
        this.listLoading = false
      })
    },
    handleModifyStatus(data, index) {
      this.list[index]['isEnabled'] = data.isEnabled
      change(data.id, 'isEnabled', data.isEnabled).then(response => {})
    },
    handleModifyCheckStatus(data, index) {
      this.list[index]['isCheck'] = data.isCheck
      change(data.id, 'isCheck', data.isCheck).then(response => {})
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">

</style>
